<?php

namespace app\common\library;

use app\admin\model\order\AppManage;
use app\admin\model\share\ShareUser;
use app\common\library\TLSSigAPIv2;
use think\Db;

class IM
{
    public $appId;
    public $key;
    public $identifier;
    public $UserSig;
    public $random;

    public function __construct()
    {
        $this->appId = config('site.IM_AppID', '1400765204');
        $this->key = config('site.IM_key', '578f96825f4d6999f9a7ded16e727eebf75793e734135fd9874180d0eb31ad68');
        $this->identifier = config('site.IM_identifier', 'administrator');
        $this->UserSig = (new TLSSigAPIv2($this->appId, $this->key))->genUserSig($this->identifier);
        $this->random = random_int(1, 99999999);
    }

    public function test()
    {
        $api = new TLSSigAPIv2($this->appId, $this->key);
        $sig = $api->genUserSig('xiaojun');
        echo $sig . "\n";
        $init_time = 0;
        $expire = 0;
        $err_msg = '';
        $ret = $api->verifySig($sig, 'xiaojun', $init_time, $expire, $err_msg);
        if (!$ret) {
            echo $err_msg . '\n';
        } else {
            echo "verify ok expire $expire init time $init_time\n";
        }
        $userbuf = '';
        $ret = $api->verifySigWithUserBuf($sig, 'xiaojun', $init_time, $expire, $userbuf, $err_msg);
        if (!$ret) {
            echo $err_msg . '\n';
        } else {
            echo "verify ok expire $expire init time $init_time userbuf $userbuf\n";
        }
        $sig = $api->genPrivateMapKey('xiaojun', 86400 * 180, 10000, 255);
        echo $sig . '\n';
        $sig = $api->genPrivateMapKeyWithStringRoomID('xiaojun', 86400 * 180, "aaa", 255);
        echo $sig . '\n';
        $init_time = 0;
        $expire = 0;
        $err_msg = '';
        $ret = $api->verifySig($sig, 'xiaojun', $init_time, $expire, $err_msg);
        if (!$ret) {
            echo $err_msg . '\n';
        } else {
            echo "verify ok expire $expire init time $init_time\n";
        }
        $userbuf = '';
        $ret = $api->verifySigWithUserBuf($sig, 'xiaojun', $init_time, $expire, $userbuf, $err_msg);
        if (!$ret) {
            echo $err_msg . '\n';
        } else {
            echo "verify ok expire $expire init time $init_time userbuf $userbuf\n";
        }
    }

    /*
     * desc:导入腾讯IM账号
     * auth:wxfeng
     * time:2022.11.24
     */
    public function account_import($UserID, $username)
    {
        $im_url = "https://console.tim.qq.com/v4/im_open_login_svc/account_import?sdkappid=" . $this->appId . "&identifier=" . $this->identifier . "&usersig=" . $this->UserSig . "&random=" . $this->random . "&contenttype=json";
        $url = Db::name("config")->where(['name' => 'url'])->find();
        $app_id = (new AppManage())->getAppId($url['value']);
        //默认头像
        $config = json_decode(\addons\shopro\model\Config::get(['name' => 'user'])->value, true);
        $avator = cdnurl($config['avatar'], true);
        $option = [
            "UserID" => $app_id['id'] . '_' . $UserID,
            'Nick' => $username,
            'FaceUrl' => $avator
        ];
        $client = new \GuzzleHttp\Client();
        $res = $client->request('POST', $im_url, [
            'body' => json_encode($option)
        ]);
        $req = $res->getBody()->getContents();
        $api_data = json_decode($req, true);
        //错误码，0表示成功，非0表示失败
        if ($api_data['ErrorCode']) {
            trace($api_data['ErrorInfo'], "error");
        }
        return $api_data['ErrorCode'] == 0;
    }

    /*
     * desc:修改腾讯IM账号资料
     * auth:wxfeng
     * time:2022.11.24
     */
    public function portrait_set($UserID, $nickname = "", $avator = "")
    {
        //更新通讯录资料
        Db::name("user_friends")->where(['f_uid' => $UserID])->update(['f_nickname' => $nickname, 'f_avatar' => $avator]);

        $im_url = "https://console.tim.qq.com/v4/profile/portrait_set?sdkappid=" . $this->appId . "&identifier=" . $this->identifier . "&usersig=" . $this->UserSig . "&random=" . $this->random . "&contenttype=json";
        $url = Db::name("config")->where(['name' => 'url'])->find();
        $app_id = (new AppManage())->getAppId($url['value']);
        $ProfileItem = [];
        if ($nickname) {
            $nickArray = [
                'Tag' => 'Tag_Profile_IM_Nick',
                "Value" => $nickname
            ];
            array_push($ProfileItem, $nickArray);
        }

        if ($avator) {
            $avatorArray = [
                'Tag' => 'Tag_Profile_IM_Image',
                "Value" => $avator
            ];
            array_push($ProfileItem, $avatorArray);
        }
        $option = [
            "From_Account" => $app_id['id'] . '_' . $UserID,
            'ProfileItem' => $ProfileItem,
        ];
        $client = new \GuzzleHttp\Client();
        $res = $client->request('POST', $im_url, [
            'body' => json_encode($option)
        ]);
        $req = $res->getBody()->getContents();
        $api_data = json_decode($req, true);
        //错误码，0表示成功，非0表示失败
        if ($api_data['ErrorCode']) {
            trace($api_data['ErrorInfo'], "error");
        }
        return $api_data['ErrorCode'] == 0;
    }

    /**
     * 解散群组
     */
    /**
     * @return mixed
     */
    public function destroy_group($GroupId)
    {
        $im_url = "https://console.tim.qq.com/v4/group_open_http_svc/destroy_group?sdkappid=" . $this->appId . "&identifier=" . $this->identifier . "&usersig=" . $this->UserSig . "&random=" . $this->random . "&contenttype=json";
        $option = [
            "GroupId" => $GroupId,
        ];
        $client = new \GuzzleHttp\Client();
        $res = $client->request('POST', $im_url, [
            'body' => json_encode($option)
        ]);
        $req = $res->getBody()->getContents();
        $api_data = json_decode($req, true);
        //错误码，0表示成功，非0表示失败
        if ($api_data['ErrorCode']) {
            trace($api_data['ErrorCode'] . $api_data['ErrorInfo'], "error");
        }
        return $api_data['ErrorCode'] == 0;
    }

    /**
     * 上下级添加好友关系
     */
    public function make_relation($user_id, $friend_id)
    {
        $pid = $user_id;
        $child_id = $friend_id;
        if (empty($pid) || empty($child_id)) {
            return false;
        }
        $parent = \addons\shopro\model\User::where(['id' => $pid])->field('id,nickname,mobile,avatar')->find();
        $child = \addons\shopro\model\User::where(['id' => $child_id])->field('id,nickname,mobile,avatar')->find();
        if (!$parent || !$child) {
            trace('用户信息不存在或已删除。', 'error');
            return false;
        }
        $r_map = [
            'user_id' => $pid,
            'f_uid' => $child_id,
            'relation' => 1
        ];
        $c_map = [
            'user_id' => $child_id,
            'f_uid' => $pid,
            'relation' => 1
        ];
        $is_friend = Db::table('user_friends')->where($r_map)->count();
        $is_relation = Db::table('user_friends')->where($c_map)->count();
        if ($is_relation || $is_friend) {
            trace('该上下级已存在好友关系。', 'error');
            return false;
        }
        $parent['role'] = ShareUser::where(['user_id' => $pid])->value('role');
        $child['role'] = ShareUser::where(['user_id' => $child_id])->value('role');
        $data = [
            [
                'user_id' => $pid,
                'f_uid' => $child_id,
                'f_nickname' => $child['nickname'],
                'f_mobile' => $child['mobile'],
                'f_avatar' => $child['avatar'],
                'f_role' => $child['role'],
                'relation' => 1,//1=正常,2=黑名单,3=申请添加
                'createtime' => time(),
            ],
            [
                'user_id' => $child_id,
                'f_uid' => $pid,
                'f_nickname' => $parent['nickname'],
                'f_mobile' => $parent['mobile'],
                'f_avatar' => $parent['avatar'],
                'f_role' => $parent['role'],
                'relation' => 1,//1=正常,2=黑名单,3=申请添加
                'createtime' => time(),
            ]
        ];
        $res = Db::table('user_friends')->insertAll($data);
        return $res;
    }


    //注销用户时删除好友关系以及腾讯IM账号
    public function del_relation($user_id)
    {
        $map = [
            'user_id' => $user_id,
        ];
        $or_map = [
            'f_uid' => $user_id,
        ];
        $res = Db::table('user_friends')
            ->where(function ($query) use ($map) {
                $query->where($map);
            })->whereOr(function ($query) use ($or_map) {
                $query->where($or_map);
            })->delete();
        return $res;
        //删除IM账号
        //71000	删除帐号失败。仅支持删除体验版帐号，您当前应用为专业版，暂不支持帐号删除
//        $im_url = "https://console.tim.qq.com/v4/im_open_login_svc/account_delete?sdkappid=" . $this->appId . "&identifier=" . $this->identifier . "&usersig=" . $this->UserSig . "&random=" . $this->random . "&contenttype=json";
//        $option = [
//            "DeleteItem" => [["UserID" => $user_id]],
//        ];
//        $client = new \GuzzleHttp\Client();
//        $res = $client->request('POST', $im_url, [
//            'body' => json_encode($option)
//        ]);
//        $req = $res->getBody()->getContents();
//        $api_data = json_decode($req, true);
//        //错误码，0表示成功，非0表示失败
//        if ($api_data['ErrorCode']) {
//            trace($api_data['ErrorCode'] . $api_data['ErrorInfo'], "error");
//        }
//        return $api_data['ErrorCode'] == 0;
    }

    /**
     * 获取群成员信息
     */
    public function get_group_member_info($GroupId)
    {
        $im_url = "https://console.tim.qq.com/v4/group_open_http_svc/get_group_member_info?sdkappid=" . $this->appId . "&identifier=" . $this->identifier . "&usersig=" . $this->UserSig . "&random=" . $this->random . "&contenttype=json";
        $option = [
            "GroupId" => $GroupId,
        ];
        $client = new \GuzzleHttp\Client();
        $res = $client->request('POST', $im_url, [
            'body' => json_encode($option)
        ]);
        $req = $res->getBody()->getContents();
        $data = json_decode($req, true);
        return $data;
    }
    /**
     * 创建群聊
     */
    public function creatre_group($UserID,$type=0)
    {
        $im_url = "https://console.tim.qq.com/v4/group_open_http_svc/create_group?sdkappid=" . $this->appId . "&identifier=" . $this->identifier . "&usersig=" . $this->UserSig . "&random=" . $this->random . "&contenttype=json";
        $url = Db::name("config")->where(['name' => 'url'])->find();
        $nickname = Db::name("user")->where(['id'=>$UserID])->value('nickname');
        $app_id = (new AppManage())->getAppId($url['value']);

        $l = strlen($nickname);
        if($type == 1){
            if($l > 10){
                $nickname = mb_substr($nickname,0,3,'utf-8');
                $name = $nickname."...创富群";
            }else{
                $name = $nickname."创富群";
            }
            $GroupId = 'top'.$app_id['id'] . '_' . $UserID."_2";
            $Notification = "创富群创建成功";
        }else{
            if($l > 10){
                $nickname = mb_substr($nickname,0,3,'utf-8');
                $name = $nickname."...创富种子群";
            }else{
                $name = $nickname."创富种子群";
            }
            $Notification = "创富种子群创建成功";
            $GroupId = 'top'.$app_id['id'] . '_' . $UserID."_3";
        }

        $option = [
            "Owner_Account" => $app_id['id'] . '_' . $UserID,
            "GroupId" => $GroupId,
            "Notification" => $Notification,
            'Type' => 'Private',
            'Name' => $name
        ];
        $client = new \GuzzleHttp\Client();
        $res = $client->request('POST', $im_url, [
            'body' => json_encode($option)
        ]);
        $req = $res->getBody()->getContents();
        $api_data = json_decode($req, true);
        //错误码，0表示成功，非0表示失败
        $re_data = [];
        if ($api_data['ErrorCode']) {
            trace($api_data['ErrorInfo'], "error");
        }else{
            $re_data['GroupId'] = $api_data['GroupId'];
        }
        $re_data['ErrorCode'] = $api_data['ErrorCode'];

        $re_data['ErrorInfo'] = $api_data['ErrorInfo'];
        return $re_data;
    }
    public function add_members($GroupId,$Member_Account)
    {
        $im_url = "https://console.tim.qq.com/v4/group_open_http_svc/add_group_member?sdkappid=" . $this->appId . "&identifier=" . $this->identifier . "&usersig=" . $this->UserSig . "&random=" . $this->random . "&contenttype=json";
        $url = Db::name("config")->where(['name' => 'url'])->find();
        $app_id = (new AppManage())->getAppId($url['value']);
        //默认头像
        $config = json_decode(\addons\shopro\model\Config::get(['name' => 'user'])->value, true);
        $avator = cdnurl($config['avatar'], true);
        $l['Member_Account'] = $Member_Account;
        $list[] =$l;
        $option = [
            "GroupId" => $GroupId,
            'MemberList' => $list
        ];
        $client = new \GuzzleHttp\Client();
        $res = $client->request('POST', $im_url, [
            'body' => json_encode($option)
        ]);
        $req = $res->getBody()->getContents();
        $api_data = json_decode($req, true);
        //错误码，0表示成功，非0表示失败
        $re_data = [];
        if ($api_data['ErrorCode']) {
            trace($api_data['ErrorInfo'], "error");
        }
        $re_data['ErrorCode'] = $api_data['ErrorCode'];
        $re_data['ErrorInfo'] = $api_data['ErrorInfo'];
        return $re_data;
    }
    public function add_group_msg($GroupId,$msg='会员拓客群创建成功',$uid)
    {
        $im_url = "https://console.tim.qq.com/v4/group_open_http_svc/send_group_msg?sdkappid=" . $this->appId . "&identifier=" . $this->identifier . "&usersig=" . $this->UserSig . "&random=" . $this->random . "&contenttype=json";

        $url = Db::name("config")->where(['name' => 'url'])->find();
        $app_id = (new AppManage())->getAppId($url['value']);
        $l['MsgType'] = 'TIMTextElem';
        $l['MsgContent']['Text'] = $msg;
        $list[] =$l;
        $option = [
            "GroupId" => $GroupId,
            "From_Account" => $app_id['id'] . '_' . $uid,
            "Random" => substr(time(),-5),
            'MsgBody' => $list
        ];
        $client = new \GuzzleHttp\Client();
        $res = $client->request('POST', $im_url, [
            'body' => json_encode($option)
        ]);
        $req = $res->getBody()->getContents();
        $api_data = json_decode($req, true);
        //错误码，0表示成功，非0表示失败
        $re_data = [];
        if ($api_data['ErrorCode']) {
            trace($api_data['ErrorInfo'], "error");
        }
        $re_data['ErrorCode'] = $api_data['ErrorCode'];
        $re_data['ErrorInfo'] = $api_data['ErrorInfo'];
        return $re_data;
    }
}
